package com.example.paint_gradient;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposeShader;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @author huangzehui
 * @date 2/7/2024 上午9:26 周二
 * @description Paint 画笔的高级使用
 * <p>
 * https://www.bilibili.com/video/BV1aK4y1Y71n/?p=3&spm_id_from=pageDriver&vd_source=e07cc8cc94eb22bd76722071b03cd199
 */
public class GradientLayout extends View {
    public GradientLayout(Context context) {
        this(context, null);
    }

    public GradientLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GradientLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    private Paint mPaint;

    private Shader mShader;

    private Bitmap mBitmap;

    private void initPaint() {
        mPaint = new Paint();

        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);

        mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.pic);
    }


    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);

        // 线性渐变
//        mShader = new LinearGradient(0, 0, 500, 500, new int[]{Color.GREEN, Color.RED}, null, Shader.TileMode.CLAMP);
//        canvas.drawRect(0, 0, 500, 500, mPaint);

        // 环形渐变
//        mShader = new RadialGradient(250,250, 250, new int[] {Color.RED,Color.BLUE, Color.DKGRAY, Color.YELLOW}, null, Shader.TileMode.REPEAT);

        // 扫描渲染
        //mShader = new SweepGradient(250,250, new int[]{Color.RED,Color.GREEN, Color.BLUE, Color.YELLOW, Color.BLACK},null);

        // 位图渲染
//        mShader = new BitmapShader(mBitmap, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR);

        // 组合渲染
        BitmapShader bitmapShader = new BitmapShader(mBitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
        LinearGradient linearGradient = new LinearGradient(0,0,250,250,new int[] {
                Color.RED,
                Color.GREEN,
                Color.BLUE
        },null,Shader.TileMode.CLAMP);
        mShader = new ComposeShader(bitmapShader,linearGradient, PorterDuff.Mode.MULTIPLY);

        mPaint.setShader(mShader);
//        canvas.drawCircle(250,250, 250, mPaint);
        canvas.drawRect(0,0,250,250, mPaint);
    }
}
